
	<?php include './dbInclude.php';?>
    <?php
    ob_start();
    session_start();
     
    $username = $_POST['email'];
    $password = $_POST['pwd'];
	try { 	
	$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

			$sql = "CALL `authenticate_user`(:email,:pwd, @poutcode, @pout_role, @pout_acc_num,@pout_clientID, @pout_message)";
			$stmt = $dbh->prepare($sql);
		 
			$stmt->bindParam(':email', $username, PDO::PARAM_STR);
			$stmt->bindParam(':pwd', $password, PDO::PARAM_STR);
			
			$stmt->execute();
			$stmt->closeCursor();
			// execute the second query to get customer's level
			$r = $dbh->query("SELECT @poutcode AS code, @pout_message AS msg, @pout_clientID AS clientID, @pout_role as pout_role, @pout_acc_num as pout_acc_num")->fetch(PDO::FETCH_ASSOC);
			if ($r) {
				$code = $r['code'];
				$msg = $r['msg'];
				$clientID = $r['clientID'];
				$acc_num = $r['pout_acc_num'];
				$role = $r['pout_role'];
				if($code == "S" && $role=="A"){
					session_regenerate_id();
					$_SESSION['sess_client_id'] = $clientID;
					$_SESSION['sess_acc_num'] = $acc_num;
					$_SESSION['sess_role'] = $role;
					session_write_close();
					header('Location: ../php/admin.php');
				}else if($role=="C"){
					if($code == "D"){
						header('Location: ../index.php?msg='.$msg);
					}else if($code == "S"){
						$_SESSION['sess_client_id'] = $clientID;
						$_SESSION['sess_acc_num'] = $acc_num;
						$_SESSION['sess_role'] = $role;
						header('Location: ../php/homeScreen.php');
					}else{
						header('Location: ../index.php?msg='.$msg);
						
					}
					
				}
			}
		} catch (Exception $e) {
		  $dbh->rollBack();
		  echo "Failed: " . $e->getMessage();
		}	
    ?>
